const app = getApp();
import { jscode2session, openLogin, BootPage } from "../../api/homePage"
import { setStorage, getStorage } from "../../utils/localStorage"
import { getAddress } from "../../utils/address"
import { baseUrl } from "../../api/request"
Page({
    data: {
        data: {},
        imgUrl: baseUrl,
    },
    onLoad(options) {
        wx.clearStorage(); //清除页面缓存
        this.getInfo();
        setTimeout(() => {
            this.login();
        }, 3000);
    },
    onShow() {

    },
    onReady() {
    },
    //获取页面配置信息
    getInfo() {
        BootPage().then(res => {
            this.setData({
                data: res.data.data
            });
        });
    },
    // 获取code
    login() {
        wx.login({
            timeout: 30000,
            success: (res) => {
                if (res.code) {
                    //登录凭证效验
                    jscode2session({ jsCode: res.code }).then(response => {
                        // console.log(response, 'response');
                        if (response.data.code === 200) {
                            setStorage("session_key", response.data.data.session_key);
                            setStorage("openId", response.data.data.openid);
                            this.getOpenLogin(response.data.data.openid, response.data.data.session_key);
                        } else {
                            this.errorMsg(2000, '登录凭证效验失败' + response.data.msg);
                        };
                    });
                } else {
                    this.errorMsg(2000, '登录失败！' + res.errMsg);
                };
            }
        });
    },
    //使用oppenId登录
    async getOpenLogin(openId, sessionKey) {
        let addRes = await getAddress();  //获取当前登录所在地址
        let { location, address_component, address_reference } = addRes.result,
            data = {
                wxOpenid: openId,   //用户的openId
                longitude: location.lng,
                latitude: location.lat,
                province: address_component.province,  //省
                city: address_component.city,  //市
                district: address_component.district, //区
                town: address_reference.town.title //镇
            };
        setStorage('latLng', { lat: location.lat, lng: location.lng });
        openLogin(data).then(res => {
            let { code, data, msg } = res.data;
            if (code === 200) {
                setStorage('user', data);
                setStorage('token', data.uuid);
                app.globalData.townName = data.townShipName;
                //根据flagLogin的状态判断他是老用户还是新用户
                data.loginFlag ? wx.redirectTo({ url: '/pages/recommendType/index' }) : wx.redirectTo({ url: '/pages/index/index' });
            } else {
                this.errorMsg(2000, msg);
            };
        });

    },

    //报错提示
    errorMsg(second, msg) {
        wx.showToast({
            icon: 'none',
            title: msg,
            mask: true,
            duration: second
        });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})